package com.qf.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import javax.xml.transform.Result;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Description: 公用常量
 * @Data: 2022/8/22 23:15
 * @Pacakge: com.qf.utils
 * @ClassName: DruidJdbcUtils
 * @Author: fan
 * 德鲁伊工具类
 */
public class DruidJdbcUtils {
    //基于数据源DataSource,数据源获取对应的Connection
    private static DataSource ds;
    //数据库连接对象
    private static ThreadLocal<Connection> t1 = new ThreadLocal<>();
    //构造函数
    private DruidJdbcUtils(){

    }
    //静态代码块
    static{
        try {
            //1>获取resource下的配置文件
            //1.1>获取属性集合列表中的内容
            //properties继承Hashtable--->就是一个map
            Properties properties = new Properties();
            //1.2>加载配置文件
            //输入流对象
            //通过类加载器获取对应的输入流对象
            //类加载器如何获取?先获取对应的字节码文件对象Class
            InputStream resourceAsStream = DruidJdbcUtils.class.getClassLoader().getResourceAsStream("Druid.properties");
            //1.3>加载输入流[加载对应的一个配置文件,读取配置文件中的内容将其加载(k:v)]
            properties.load(resourceAsStream);
            //2>通过DruidSourceFactory创建数据源
            ds=DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //获取数据源
    public static DataSource getDataSource(){
        return ds;
    }
    //获取数据库连接对象
    public static Connection getConnection(){
        try {
            Connection connection = null;
            t1.get();
            if (connection == null){
                connection=ds.getConnection();
                t1.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //释放资源
    public void close(ResultSet resultSet, Statement statement,Connection connection){
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //释放资源
    public static void close(Statement statement,Connection connection){
        close(statement,connection);

    }
}
